const sqlOrm = require('../common/sqlModel');
var request = require('../common/Request');
var utils = require('../common/utils');
const path = require("path")
const rate = require("../common/config.json").rate
const Taobao = require("../controllers/taobao")
const xlsx = require('node-xlsx');
let sentTime = 3;
// const connectionLocalhot = require("./commonModel").connectionLocalhot
let loginFlag = 0;
// var j = request.jar()
const RequestGet = request.RequestGet
const RequestDown = request.RequestDown
var dirPath = path.join(__dirname, "../orderfile");
dirPath = path.join(dirPath, "order.xls");

var requestPost = require("../common/Request").RequestPost
var RequestPostFom = require("../common/Request").RequestPostFom
const config = require("../common/config")
const mm = require("../common/config").mm

class Init {
    async initGlobal() {
        let globalInfo = await sqlOrm.global.findAsync();
        if (globalInfo.length > 0) {
            for (var i of globalInfo) {
                if (i.id == 1) {
                    global.rate = JSON.parse(i.value) / 100
                } else if (i.id == 2) {
                    global.cookie2 = i.value
                } else if (i.id == 3) {
                    global.token = i.value
                } else if (i.id == 4) {
                    global.payEndTime = i.value
                } else if (i.id == 5) {
                    global.adzoneidNum = i.value
                } else if (i.id == 6) {
                    global.initMoney = i.value
                } else if (i.id == 10) {
                    global.MaxMoney = i.value
                }
            }
        }

        setInterval(async function () {
            let globalInfo = await sqlOrm.global.findAsync();
            if (globalInfo.length > 0) {
                for (var i of globalInfo) {
                    if (i.id == 1) {
                        global.rate = JSON.parse(i.value) / 100
                    } else if (i.id == 2) {
                        global.cookie2 = i.value
                    } else if (i.id == 3) {
                        global.token = i.value
                    } else if (i.id == 4) {
                        global.payEndTime = i.value
                    } else if (i.id == 5) {
                        global.adzoneidNum = i.value
                    } else if (i.id == 6) {
                        global.initMoney = i.value
                    } else if (i.id == 10) {
                        global.MaxMoney = i.value
                    }
                }
            }
        }, 20 * 1000)
    }

    async GetOrderVerTimeCookie() {
        // 隔一段时间取获取订单信息 14 状态才是订单成功 (一天)
        setInterval(async function () {
            let nowTime = new Date().getTime()
            let lastDate = new Date(nowTime - 30 * 24 * 3600 * 1000).getTime();
            let url = `https://pub.alimama.com/report/getTbkPaymentDetails.json?startTime=${utils.changeToString(lastDate)}&endTime=${utils.changeToString(nowTime)}&payStatus=&queryType=1&toPage=1&perPageSize=200&total=&t=${new Date().getTime()}&pvid=&_tb_token_=${global.token}&_input_charset=utf-8`

            let cookies = {
                '_tb_token_': global.token,
                't': new Date().getTime(),
                'v': '0',
                'cookie2': global.cookie2,
            };
            let cookie_val = utils.formatCook(cookies);
            let headers = {
                'authority': 'pub.alimama.com',
                'method': 'GET',
                'path': '/common/code/getAuctionCode.json?auctionid=575830334240&adzoneid=78346129&siteid=23532937&scenes=1&tkFinalCampaign=1&t=' + new Date().getTime() + '&_tb_token_=' + global.token + '&pvid=10_220.200.59.244_622_' + new Date().getTime(),
                'referer': 'https://pub.alimama.com/promo/search/index.htm?q=%E5%93%87%E5%93%88%E5%93%88ad%E9%92%99%E5%A5%B6220ml&_t=1536243536417&toPage=1&dpyhq=1',
                'x-requested-with': 'XMLHttpRequest',
                'C': cookie_val,
            };
            let resInfo = await  RequestGet(url, {}, headers);
            console.log("resInfoxxxxxxxxxxxxxxxxxxxxxxxxxx", resInfo)
            resInfo = utils.changeToObj(resInfo);
            if (resInfo.data) {
                let orderInfo = resInfo.data.paymentList;
                for (let i of orderInfo) {
                    let mysqlOrderInfo = sqlOrm.order.findAsync({
                        taobaoTradeParentId: i.taobaoTradeParentId,
                        auctionId: i.auctionId,
                        toMyuser: 0
                    });
                    if (mysqlOrderInfo.length > 0) {
                        mysqlOrderInfo[0].toMyuser = JSON.parse(i.totalAlipayFeeString) * 0.9 * golden.rate / rate * i.auctionNum;
                        mysqlOrderInfo[0].toMyuser = mysqlOrderInfo[0].toMyuser.toFixed(2)

                        var userId = mysqlOrderInfo[0].userID
                        let accountInfo = sqlOrm.app_account.findAsync({id: userId});
                        if (accountInfo.length > 0) {
                            // 加钱
                            accountInfo[0].money = JSON.parse(mysqlOrderInfo[0].money) + JSON.parse(i.totalAlipayFeeString) * rate * i.auctionNum;
                            accountInfo[0].money = accountInfo[0].money.toFixed(2)
                            await  mysqlOrderInfo[0].saveAsync();
                        }
                    }
                }
            }
        }, 24 * 3600 * 1000)
    }

    async GetOrderVerTimeDown() {

        // 隔一段时间取获取订单信息 14 状态才是订单成功
        setInterval(async function () {
            // let nowTime = utils.changeToString(new Date().getTime());
            // let lastDate = utils.changeToString(new Date(nowTime - 90 * 24 * 3600 * 1000).getTime());
            //
            // let lastOrder = sqlOrm.taobaokeOrder.findAsync({},1,["createTime","Z"]);
            // if(lastOrder.length > 0){
            //     lastDate = lastOrder[0].createTime
            // }
            // await downLoadOrderFile(nowTime,lastDate)
            await SaveOrders()
            // setTimeout(async function () {
            //
            // },2000);

        }, 5 * 60 * 1000)
    }

    async GetOrderVerTimeDown2() {
        // 隔一段时间取获取订单信息 14 状态才是订单成功
        let OrderInfo = await getOrderInfoCook(null, [], 1);
        setInterval(async function () {
            let orderArray = []
            let OrderInfo = await getOrderInfoCook(null, orderArray, 1);
            console.log("OrderInfo", OrderInfo)
        }, 2 * 60 * 60 * 1000)
    }

    async initOrder() {
        // 隔一段时间取获取订单信息 14 状态才是订单成功
        setInterval(async function () {
            let lastTimeMysql = await sqlOrm.needSearchOrder.findAsync({value: 1}, 1);
            if (lastTimeMysql.length <= 0) {
                return
            }

            let lastTime = lastTimeMysql[0].time
            let url = `http://apiorder.vephp.com/order?vekey=V00000355Y39162829&start_time=${lastTime}&span=1200`
            let taobaoResNew = await RequestGet(url, {})

            var reg = /trade_parent_id+/g;
            let gettrade_parent_idsArray = []
            gettrade_parent_idsArray = gettrade_parent_ids(reg, taobaoResNew, gettrade_parent_idsArray)

            var reg = /trade_id+/g;
            let trade_id_idsArray = []
            trade_id_idsArray = trad_ids(reg, taobaoResNew, trade_id_idsArray)
            taobaoResNew = utils.changeToObj(taobaoResNew)
            console.log("gettrade_parent_idsArray", gettrade_parent_idsArray)
            let returnInfo = await saveOrderInfo(taobaoResNew, gettrade_parent_idsArray, trade_id_idsArray)
            if (returnInfo == 1) {
                lastTimeMysql[0].value = 0;
                lastTimeMysql[0].saveAsync()
            }
            // InitSelf.initOldOrder()
        }, 60 * 1000)
    }


    async initOldOrder() {
        // 隔一段时间取获取订单信息 14 状态才是订单成功
        setInterval(async function () {
            let lastTimeMysql = await sqlOrm.taobaokeOrder.findAsync({}, 1, ["createTime", "Z"])
            let lastTime = "2018-09-01 00:00:00"
            if (lastTimeMysql.length > 0) {
                lastTime = lastTimeMysql[0].createTime
            }
            let lastUpdateTime = await  sqlOrm.global.findAsync({id: 7})
            let isOpen = await  sqlOrm.global.findAsync({id: 9})
            if (lastUpdateTime.length <= 0) {
                await sqlOrm.global.createAsync({id: 7, value: lastTime})
            }

            if (isOpen.length <= 0) {
                await sqlOrm.global.createAsync({id: 9, value: 1})
            }
            let UpdateTime = await  sqlOrm.global.findAsync({id: 7})
            isOpen = await  sqlOrm.global.findAsync({id: 9})
            if (isOpen[0].value == 0) {
                return
            }
            lastTime = UpdateTime[0].value

            let newTime = new Date(UpdateTime[0].value).getTime() + 1200 * 1000

            if (newTime >= new Date().getTime()) {
                return
            }

            UpdateTime[0].value = utils.changeToStringDate(newTime)// new Date(newTime).toLocaleString();
            UpdateTime[0].saveAsync()

            let url = `http://apiorder.vephp.com/order?vekey=V00000355Y39162829&start_time=${lastTime}&span=1200`
            let taobaoResNew = await RequestGet(url, {})

            var reg = /trade_parent_id+/g;
            let gettrade_parent_idsArray = []
            gettrade_parent_idsArray = gettrade_parent_ids(reg, taobaoResNew, gettrade_parent_idsArray)

            var reg = /trade_id+/g;
            let trade_id_idsArray = []
            trade_id_idsArray = trad_ids(reg, taobaoResNew, trade_id_idsArray)
            taobaoResNew = utils.changeToObj(taobaoResNew)
            console.log("gettrade_parent_idsArray", gettrade_parent_idsArray)
            await saveOrderInfo(taobaoResNew, gettrade_parent_idsArray, trade_id_idsArray)
            // InitSelf.initOldOrder()
        }, 10 * 1000)
    }

    async findUrlByCookie() {
        setInterval(async function () {
            let needGetItemId = await sqlOrm.needGetItemId.findAsync({}, 1);
            if (needGetItemId.length <= 0) {
                return
            }
            let auctionid = needGetItemId[0].id
            let t = new Date().getTime()
            let params = {
                'auctionid': auctionid,
                'adzoneid': "25023000068",
                'siteid': '22556559',
                'scenes': '1',
                'tkFinalCampaign': '1',
                't': t,
                '_tb_token_': global.token,
                'pvid': '10_47.98.122.59_622_' + t,
            }

            let cookies = {
                '_tb_token_': global.token,
                't': new Date().getTime(),
                'v': '0',
                'cookie2': global.cookie2,
            };
            let cookie_val = utils.formatCook(cookies);
            let headers = {
                'authority': 'pub.alimama.com',
                'method': 'GET',
                'path': '/common/code/getAuctionCode.json?auctionid=575830334240&adzoneid=78346129&siteid=23532937&scenes=1&tkFinalCampaign=1&t=' + new Date().getTime() + '&_tb_token_=' + global.token + '&pvid=10_47.98.122.59_622_' + new Date().getTime(),
                'referer': 'https://pub.alimama.com/promo/search/index.htm?q=%E5%93%87%E5%93%88%E5%93%88ad%E9%92%99%E5%A5%B6220ml&_t=1536243536417&toPage=1&dpyhq=1',
                'x-requested-with': 'XMLHttpRequest',
                'Cookie': cookie_val,
            };
            let info = {}
            let paramsItem = params;
            paramsItem["q"] = "https://item.taobao.com/item.htm?id=" + auctionid;

            let urlItem = 'https://pub.alimama.com/items/search.json?';
            let itemInfo = await  RequestGet(urlItem, paramsItem, urlItem);
            if (itemInfo.data) {
                info.shop_title = itemInfo.data.pageList[0].shopTitle
                info.nick = itemInfo.data.pageList[0].nick
                info.nick = itemInfo.data.pageList[0].nick
                info.seller_id = itemInfo.data.pageList[0].sellerId
                info.item_url = itemInfo.data.pageList[0].auctionUrl
                info.coupon_info = itemInfo.data.pageList[0].couponInfo
                i.coupon_info = i.coupon_info.substring(startP + 1, i.coupon_info.length - 1);
                info.zk_final_price = itemInfo.data.pageList[0].zkPrice
                info.tkCommonRate = itemInfo.data.pageList[0].commission_rate
            }
            let url = 'https://pub.alimama.com/common/code/getAuctionCode.json?';
            let resInfo = await  RequestGet(url, params, headers)
            resInfo = utils.changeToObj(resInfo);
            if (resInfo.data) {
                // {"invalidKey":null,"ok":true,"data":{"clickUrl":"https://s.click.taobao.com/t?e=m%3D2%26s%3DwquhsqtEh5IcQipKwQzePOeEDrYVVa64LKpWJ%2Bin0XLjf2vlNIV67iOYn3JEXyyDJ7ATJSEv968wYyBkjhzGLZUSAhEZ2u8Q7TT703czVD3i4uK5eGhoPotmJ1gZa8j%2BXHDWGlmriXjyb3rAtnR9hyQ%2FGb7CwMvRDJbuZDCrHt4%3D&pvid=26_120.32.92.242_753_1537164092385","couponLink":"","tkCommonRate":"10.00","taoToken":"￥SgWYbVi6fyV￥","qrCodeUrl":"//gqrcode.alicdn.com/img?type=hv&text=https%3A%2F%2Fs.click.taobao.com%2Frpf8WMw%3Faf%3D3&h=300&w=300","type":"auction","couponShortLinkUrl":null,"shortLinkUrl":"https://s.click.taobao.com/rpf8WMw"},"info":{"ok":true,"message":null}}
                // https://pub.alimama.com/items/search.json?q=%E5%A5%B3%E8%A3%85&_t=1537165926677&auctionTag=&perPageSize=50&shopTag=&t=1537165926689&_tb_token_=5a975b9868d35&pvid=10_120.32.92.242_701_1537165916780
                info.coupon_click_url = resInfo.data.couponShortLinkUrl
                if (info.coupon_click_url.length <= 1) {
                    info.shortLinkUrl = resInfo.data.clickUrl
                }
                sqlOrm.taobaoitem.createAsync(info);
                needGetItemId[0].remove()
            }
        }, 5000)
    }

    async findUrlByMsg() {
        setInterval(async function () {
            let needGetItemId = await sqlOrm.searchMsg.findAsync({}, 1);
            if (needGetItemId.length <= 0) {
                return
            }


        }, 5000)
    }

    async getAdzoneId() {
        setInterval(async function () {
            let needGetUserId = await sqlOrm.needGetUserId.findAsync({}, 1);
            if (needGetUserId.length <= 0) {
                return
            }
            let userId = needGetUserId[0].id
            let adzoneid = needGetUserId[0].adzoneid
            if (adzoneid != -1) {
                await changeChannelName(userId, adzoneid)
            } else {
                let res = await Taobao.getadzoneIdInfo(userId, true);
                let UserInfo = await  sqlOrm.app_account.findAsync({account: userId})
                if (UserInfo.length > 0) {
                    UserInfo[0].mm = res
                    await UserInfo[0].saveAsync();
                }
            }
            needGetUserId[0].remove()
        }, 10 * 60 * 1000)


        setInterval(async function () {
            let needGetUserId = await sqlOrm.EXadzoneid.countAsync({});
            if (needGetUserId >= global.adzoneidNum) {
                sentTime = 3
                return
            }
            if (needGetUserId <= 60) {
                if (sentTime > 0) {
                    // 备用的mm值被用了少于60 发3次短信
                    await utils.sentMsgInfo(18205960269, 'SMS_147970724');
                    await utils.sentMsgInfo(18695611291, 'SMS_147970724');
                    sentTime = sentTime - 1
                }

            }
            let userId = new Date().getTime()
            let adzoneId = await Taobao.getadzoneIdInfo(userId, true);
            if (adzoneId != -1)
                await sqlOrm.EXadzoneid.createAsync({channelName: userId, adzoneid: adzoneId})
            // needGetUserId[0].remove()
        }, 10 * 60 * 1000)

    }

    async updateOrder() {
        setInterval(async function () {
            let nowTime_ = new Date()
            let hour = nowTime_.getHours();
            let min = nowTime_.getMinutes();
            if (hour === 0 && min === 10) {
                let nowTime = utils.changeToString(new Date().getTime());
                let lastDate = utils.changeToString(new Date(nowTime - 90 * 24 * 3600 * 1000).getTime());
                // await downLoadOrderFile(nowTime,lastDate);
                setTimeout(async function () {
                    await  SaveOrders()
                }, 2000);

                setTimeout(async function () {
                    await updateUserMoney()
                }, 3000);
            }
        }, 60 * 1000)
    }

    async getLogin() {
        setInterval(function () {
            Taobao.getQrCode({}, {}, {}, function (res) {
                console.log("登录信息", res)
            })
        }, 5 * 1000)
    }

    // 检查退款
    async checkPayBack() {
        console.log("333333333333")
        setInterval(async function () {
            getMoneyBackOrder(1)
        }, 5 * 1000)

    }

    async InitPdOrder(){
        getPddOrders()
    }
}


var findUrlByThAPI_ = async function (itemId) {
    try {
        var mmT = mm;
        let pid = "mm_68895478_112300025_" + mmT;
        let gaoyongInfo = await  RequestGet("http://api.vephp.com/hcapi?", {
            vekey: vekey,
            para: itemId,
            pid: pid,
            detail: 1
        })
        console.log("gaoyongInfo", gaoyongInfo)
        gaoyongInfo = utils.changeToObj(gaoyongInfo);
        if (gaoyongInfo && !gaoyongInfo.error) {
            gaoyongInfo.data.coupon_share_url = gaoyongInfo.data.coupon_click_url;
            gaoyongInfo.data.commission_rate = gaoyongInfo.data.commission_rate * 100;

            if (gaoyongInfo.data.coupon_info) {
                var startP = gaoyongInfo.data.coupon_info.indexOf("减");
                gaoyongInfo.data.coupon_info = gaoyongInfo.data.coupon_info.substring(startP + 1, gaoyongInfo.data.coupon_info.length - 1);
            }
            gaoyongInfo.data.commission_rate = Math.floor(gaoyongInfo.data.commission_rate)

            var tbk_pwd = gaoyongInfo.data.tbk_pwd;
            var coupon_short_url = gaoyongInfo.data.coupon_short_url;
            var zk_final_price = gaoyongInfo.data.zk_final_price;

            gaoyongInfo.data.tbk_pwd = tbk_pwd;
            gaoyongInfo.data.coupon_short_url = coupon_short_url;
            gaoyongInfo.data.zk_final_price = zk_final_price;
            gaoyongInfo.data.phone = 0;
            gaoyongInfo.data.nick = JSON.stringify(gaoyongInfo.data.nick)
            gaoyongInfo.data.url = coupon_short_url;
            console.log("gaoyongInfo", gaoyongInfo)

            try {
                await  sqlOrm.taobaoitem.createAsync(gaoyongInfo.data);
            } catch (e) {
                console.info("重复物品")
            }
            return 1
        } else {
            return 0
        }
    } catch (e) {
        console.error("findUrlByThAPI_查詢失敗")
        return 0
    }
}

var SaveOrders = async function () {
    // 1、全部订单
    // 3、订单结算
    // 12、订单付款
    // 13、订单失效
    // 14、订单成功
    //

    try {
        let lastUpdateTime = await  sqlOrm.global.findAsync({id: 8})
        let newTime = utils.changeToStringDate(new Date().getTime())    //new Date().toLocaleString();
        if (lastUpdateTime.length <= 0) {
            await sqlOrm.global.createAsync({id: 8, value: newTime})
        } else {
            lastUpdateTime[0].value = newTime
            lastUpdateTime[0].saveAsync();
        }

        let lastTime = new Date().getTime() - 1200 * 1000;
        // new Date(lastTime).toLocaleString()
        lastTime = utils.changeToStringDate(lastTime)
        let url = `http://apiorder.vephp.com/order?vekey=V00000355Y39162829&start_time=${lastTime}&span=1200`;
        let taobaoResNew = await RequestGet(url, {})

        var reg = /trade_parent_id+/g;
        let gettrade_parent_idsArray = [];
        gettrade_parent_idsArray = gettrade_parent_ids(reg, taobaoResNew, gettrade_parent_idsArray);

        var reg = /trade_id+/g;
        let trade_id_idsArray = []
        trade_id_idsArray = trad_ids(reg, taobaoResNew, trade_id_idsArray);

        taobaoResNew = utils.changeToObj(taobaoResNew)
        console.log("gettrade_parent_idsArray", gettrade_parent_idsArray)
        await saveOrderInfo(taobaoResNew, gettrade_parent_idsArray, trade_id_idsArray);

        // let OrderInfo = await sqlOrm.taobaokeOrder.findAsync({payStatusCode:[2,3]},["createTime"]);
        // if (OrderInfo.length > 0){
        //     for(var obj of OrderInfo){
        //         let startTime = obj.createTime
        //         let url = `http://api.vephp.com/order?vekey=V00000355Y39162829&start_time=${startTime}&span=60`
        //         let taobaoRes = await RequestGet(url,{})
        //         var  reg = /trade_parent_id+/g;
        //         let gettrade_parent_idsArray = []
        //          gettrade_parent_idsArray = gettrade_parent_ids(reg,taobaoRes,gettrade_parent_idsArray)
        //         console.log("gettrade_parent_idsArray 111",gettrade_parent_idsArray)
        //         var  reg = /trade_id+/g;
        //         let trade_id_idsArray = []
        //         trade_id_idsArray = trad_ids(reg,taobaoRes,trade_id_idsArray)
        //         console.log("trade_id_idsArray 111",trade_id_idsArray)
        //         console.log("taobaoRes 111",taobaoRes)
        //         taobaoRes = utils.changeToObj(taobaoRes)
        //         await updateOrderInfo(taobaoRes,gettrade_parent_idsArray,trade_id_idsArray)
        //         sleep(1000)
        //     }
        // }

        // let orderArray = []
        // let OrderInfo = await getOrderInfoCook(orderArray,1);
        // if(OrderInfo != 0){
        //     await updateOrderInfo(orderArray)
        // }
    } catch (e) {
        console.error("SaveOrders err", e)
    }

}

var gettrade_parent_ids = function (trade_parent_id, taobaoRes, tempArray) {
    var res1 = trade_parent_id.exec(taobaoRes)
    if (res1 != null) {
        var temp = taobaoRes.substring(res1.index + 17, res1.index + 35)
        tempArray.push(temp)
        gettrade_parent_ids(trade_parent_id, taobaoRes, tempArray)
    }
    return tempArray
}

var trad_ids = function (trade_parent_id, taobaoRes, tempArray) {
    var res1 = trade_parent_id.exec(taobaoRes)
    if (res1 != null) {
        var temp = taobaoRes.substring(res1.index + 10, res1.index + 28)
        tempArray.push(temp)
        trad_ids(trade_parent_id, taobaoRes, tempArray)
    }
    return tempArray
}


var saveOrderInfo = async function (taobaoRes, trade_parent_ids, trade_ids) {

    try {
        if (taobaoRes.data && taobaoRes.data.length > 0) {
            let Orders = taobaoRes.data;
            let returnInfo = 0
            for (var i = 0; i < Orders.length; i++) {
                console.log("iiiiiii is", i);
                let order = Orders[i]
                order.trade_parent_id = trade_parent_ids[i]
                order.trade_id = trade_ids[i]
                let tk_status = order.tk_status;
                let commission_rate = order.commission_rate
                commission_rate = JSON.parse(commission_rate)

                let orederTime = 0
                let payStatusCode = 3;
                let payStatus = ""
                if (tk_status == 3) {
                    payStatus = "返利中";
                    payStatusCode = 3
                } else if (tk_status == 12) {
                    payStatus = "返利中"
                    payStatusCode = 2
                } else if (tk_status == 13) {
                    payStatusCode = 13
                    payStatus = "订单失效"
                } else if (tk_status == 14) {
                    payStatus = "返利中"
                    payStatusCode = 3
                }
                orederTime = new Date().getTime()
                let discountAndSubsidyToString = (JSON.parse(order.income_rate) * 0.9 * global.rate * commission_rate * 100).toFixed(2) + "%";

                let orderInfo = await  sqlOrm.taobaokeOrder.findAsync({
                    taobaoTradeParentId: order.trade_parent_id,
                    taobaoTradeSubId: order.trade_id,
                    itemId: order.num_iid
                })
                if (orderInfo.length > 0) {
                    returnInfo = 1
                    continue
                }

                let income_rate = (JSON.parse(order.income_rate) * 100).toFixed(2)

                // pub_share_pre_fee 有付钱就有了  commission ，结算才有
                let pub_share_pre_fee = order.pub_share_pre_fee;
                pub_share_pre_fee = JSON.parse(pub_share_pre_fee);
                pub_share_pre_fee = Math.round(pub_share_pre_fee * global.rate * 0.9 * 100);
                let UserInfo = await sqlOrm.app_account.findAsync({account: order.adzone_name});

                if (UserInfo.length <= 0) {
                    UserInfo = await sqlOrm.app_account.findAsync({mm: order.adzone_id})
                }
                if (UserInfo.length <= 0) {
                    console.error("订单没找到用户，请手动查询")
                    returnInfo = 1
                    continue
                }

                let icon = "", shareUrl = "", url = "";
                let shareInfo = await sqlOrm.taobaoitem.findAsync({
                    /*phone:UserInfo[0].account,*/
                    num_iid: order.num_iid
                })

                let share = 0;
                if (shareInfo.length > 0) {
                    icon = shareInfo[0].pict_url;
                    if (!shareInfo[0].coupon_share_url || shareInfo[0].coupon_share_url.length <= 0) {
                        shareUrl = shareInfo[0].url;
                    } else {
                        shareUrl = shareInfo[0].coupon_share_url;
                    }
                    url = shareInfo[0].item_url;
                    share = 1
                } else {
                    // let shareInfo = await findUrlByThAPI_(order.num_iid)
                    //  if (shareInfo == 1){
                    //       shareInfo = await sqlOrm.taobaoitem.findAsync({/*phone:UserInfo[0].account,*/num_iid:order.num_iid})
                    //      if(shareInfo.length > 0){
                    //          icon = shareInfo[0].pict_url;
                    //          if(!shareInfo[0].coupon_share_url || shareInfo[0].coupon_share_url.length <=0 ){
                    //              shareUrl = shareInfo[0].url;
                    //          }else {
                    //              shareUrl = shareInfo[0].coupon_share_url;
                    //          }
                    //          url = shareInfo[0].item_url;
                    //          share = 1
                    //      }
                    //  }
                }
                if (UserInfo[0].blackUser == 1) {
                    share = 0
                }

                let feeString = order.total_commission_fee;
                let orderMysel = {
                    userId: UserInfo[0].account,  //账号
                    taobaoTradeParentId: order.trade_parent_id,  //订单id
                    taobaoTradeSubId: order.trade_id,  //子订单id
                    itemId: order.num_iid,
                    shopId: "",
                    shopName: order.seller_shop_title,
                    payPrice: order.price,  // 商品单价
                    auctionNum: order.item_num,
                    payStatus: payStatus,  // 支付状态Msg
                    payStatusCode: payStatusCode,  // 支付状态code
                    discountAndSubsidyToStringReal: income_rate,  //佣金实际比率
                    discountAndSubsidyToString: discountAndSubsidyToString,  //佣金比率
                    finalDiscountToString: order.total_commission_fee,  //佣金金额
                    totalAlipayFeeString: order.alipay_total_price,  // 付款金额
                    payMoney: order.pay_price,  // 结算金额
                    mayPay: pub_share_pre_fee,  // 预估收入
                    toMyuser: 0,  // 返回给玩家的金额 没返回0，已经返回了具体的金额
                    msg: order.item_title,
                    icon: icon,
                    url: url,
                    shareUrl: shareUrl,
                    createTime: order.create_time,
                    orederTime: orederTime,
                    share: share,
                    feeString: feeString,
                    rate:global.rate,
                    // channel:i[9],
                };


                // 保存订单
                if (UserInfo.length <= 0) {
                    console.error("订单没找到用户，请手动查询")
                } else {
                    await  sqlOrm.taobaokeOrder.createAsync(orderMysel);
                    if (payStatusCode != 13 && share == 1) {
                        let sumMayPay = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT sum(mayPay) sumMayPay FROM taobaokeorde WHERE userId = ? and share = 1 and payStatusCode in (2,3)", [UserInfo[0].account])
                        if (sumMayPay.length > 0)
                            UserInfo[0].needBackMoney = sumMayPay[0].sumMayPay
                    }
                    returnInfo = 1
                    await UserInfo[0].saveAsync();
                }
                //
            }
            return returnInfo
        }
    } catch (e) {
        console.log("入库订单失败")
        return 0
    }

}

var updateOrderInfo = async function (taobaoRes) {
    if (taobaoRes.length > 0) {

        let Orders = taobaoRes
        for (var i = 0; i < Orders.length; i++) {
            let order = Orders[i]
            let tk_status = order.payStatus;
            console.log("order.payStatus is", order.payStatus)
            let payStatusCode = 3;
            let payStatus = ""
            if (tk_status == 3) {
                payStatus = "返利中";
                payStatusCode = 3
            } else if (tk_status == 12) {
                payStatus = "返利中"
                payStatusCode = 2
            } else if (tk_status == 13) {
                payStatusCode = 13
                payStatus = "订单失效"
            } else if (tk_status == 14) {
                payStatus = "返利中"
                payStatusCode = 3
            }

            console.log("order.feeString", order.feeString)
            console.log("order.taobaoTradeParentId", order.taobaoTradeParentId)
            console.log("payStatusCode is", payStatusCode)
            // console.log("order.taobaoTradeParentId",order)
            let orderInfoNo = await  sqlOrm.taobaokeOrder.findAsync({
                taobaoTradeParentId: order.taobaoTradeParentId,
                payPrice: order.payPrice,
                itemId: order.auctionId,
                auctionNum: order.auctionNum
            })

            if (orderInfoNo.length <= 0) {
                try {
                    sqlOrm.needSearchOrder.createAsync({time: order.createTime, value: 1})
                } catch (e) {
                    console.log("已经存在需要的订单了")
                }
                continue
            }

            // if (payStatusCode == 2) {
            //     let orderInfo = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT  *  FROM taobaokeorde WHERE   taobaoTradeParentId = ? and payPrice = ? and payStatusCode = 2 and itemId = ? and auctionNum = ? and payMoney !=?",
            //         [order.taobaoTradeParentId, order.payPrice, order.auctionId, order.auctionNum, JSON.parse(order.realPayFeeString)])
            //
            //     if (orderInfo.length > 0) {
            //         orderInfo[0].payStatus = payStatus
            //         orderInfo[0].payMoney = JSON.parse(order.realPayFeeString);
            //         orderInfo[0].feeString = JSON.parse(order.tkPubShareFeeString);
            //         orderInfo[0].earningTime = order.earningTime;
            //
            //         if (/*UserInfo.length >0 && */orderInfo[0].mayPay == 0) {
            //             if (orderInfo[0].share == 1) {
            //                 let pub_share_pre_fee = order.tkPubShareFeeString;
            //                 pub_share_pre_fee = JSON.parse(pub_share_pre_fee);
            //                 pub_share_pre_fee = Math.round(pub_share_pre_fee * global.rate * 0.9 * 100);
            //                 orderInfo[0].mayPay = pub_share_pre_fee
            //                 // UserInfo[0].needBackMoney += orderInfo[0].mayPay
            //             }
            //             // await  UserInfo[0].saveAsync();
            //             orderInfo[0].payStatusCode = payStatusCode
            //         } else {
            //             console.error("没有玩家信息")
            //         }
            //         await  orderInfo[0].saveAsync()
            //     }
            // } else

            let discountAndSubsidyToString = order.discountAndSubsidyToString

            discountAndSubsidyToString =  JSON.parse(discountAndSubsidyToString.substring(0,discountAndSubsidyToString.length -2))
            console.log("discountAndSubsidyToString is:",discountAndSubsidyToString)

            if (payStatusCode == 3) {
                let orderInfo = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT  *  FROM taobaokeorde WHERE  taobaoTradeParentId = ? and payPrice = ? and payStatusCode in(1,3) and itemId = ? and auctionNum = ? and feeString !=? and discountAndSubsidyToStringReal = ?",
                    [order.taobaoTradeParentId, order.payPrice, order.auctionId, order.auctionNum, order.tkPubShareFeeString,discountAndSubsidyToString])

                if (orderInfo.length > 0) {
                    for(var j of orderInfo) {
                        let orderInfo_1 = await sqlOrm.taobaokeOrder.findAsync({id:j.id});
                        orderInfo_1[0].payMoney = JSON.parse(order.realPayFeeString);
                        orderInfo_1[0].feeString = order.tkPubShareFeeString;
                        orderInfo_1[0].earningTime = order.earningTime;
                        let pub_share_pre_fee = order.tkPubShareFeeString;
                        pub_share_pre_fee = JSON.parse(pub_share_pre_fee);
                        pub_share_pre_fee = Math.round(pub_share_pre_fee * orderInfo_1[0].rate * 0.9 * 100);
                        orderInfo_1[0].mayPay = pub_share_pre_fee
                        await  orderInfo_1[0].saveAsync()
                    }
                }

                let orderInfo_2 = await  sqlOrm.taobaokeOrder.findAsync({
                    taobaoTradeParentId: order.taobaoTradeParentId,
                    payPrice: order.payPrice,
                    payStatusCode: [2],
                    itemId: order.auctionId,
                    auctionNum: order.auctionNum,
                    discountAndSubsidyToStringReal: discountAndSubsidyToString,
                })

                if (orderInfo_2.length > 0) {
                    orderInfo_2[0].payStatus = payStatus
                    orderInfo_2[0].payStatusCode = payStatusCode
                    orderInfo_2[0].payMoney = JSON.parse(order.realPayFeeString);
                    orderInfo_2[0].feeString = order.tkPubShareFeeString;
                    orderInfo_2[0].earningTime = order.earningTime;
                    if (orderInfo_2[0].share == 1) {
                        let pub_share_pre_fee = order.tkPubShareFeeString;
                        pub_share_pre_fee = JSON.parse(pub_share_pre_fee);
                        pub_share_pre_fee = Math.round(pub_share_pre_fee * orderInfo_2[0].rate * 0.9 * 100);
                        orderInfo_2[0].mayPay = pub_share_pre_fee
                    } else {
                        console.error("没有对应的商品信息", order.auctionId)
                    }
                    await  orderInfo_2[0].saveAsync()
                }
            } else if (payStatusCode === 13) {
                let orderInfo = await  sqlOrm.taobaokeOrder.findAsync({
                    taobaoTradeParentId: order.taobaoTradeParentId,
                    payPrice: order.payPrice,
                    payStatusCode: [2, 3,13],
                    itemId: order.auctionId,
                    auctionNum: order.auctionNum,
                    discountAndSubsidyToStringReal: discountAndSubsidyToString,
                },["createTime","A"]);
                if (orderInfo.length > 0) {
                    if(orderInfo[0].payStatusCode == 13) continue

                    let UserInfo = await sqlOrm.app_account.findAsync({account: orderInfo[0].userId})
                    orderInfo[0].payStatus = payStatus
                    orderInfo[0].payMoney = JSON.parse(order.realPayFeeString);
                    orderInfo[0].feeString = order.tkPubShareFeeString;
                    orderInfo[0].payStatusCode = payStatusCode;
                    orderInfo[0].earningTime = order.earningTime;
                    await  orderInfo[0].saveAsync();

                    if (UserInfo.length > 0 && orderInfo[0].mayPay > 0) {
                        if (orderInfo[0].share == 1) {
                            let sumMayPay = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT sum(mayPay) sumMayPay FROM taobaokeorde WHERE userId = ? and share = 1 and payStatusCode in (2,3)", [orderInfo[0].userId])
                            if (sumMayPay.length > 0)
                                UserInfo[0].needBackMoney = sumMayPay[0].sumMayPay
                        }
                        await  UserInfo[0].saveAsync();
                    } else {
                        console.error("没有玩家信息13", orderInfo[0].userId)
                    }
                }
            }

        }
    }
}


var downLoadOrderFile = async function (nowTime, lastDate) {
    let url = `https://pub.alimama.com/report/getTbkPaymentDetails.json?spm=a219t.7664554.1998457203.58.295c35d9mHQB8i&queryType=1&payStatus=&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&startTime=${lastDate}&endTime=${nowTime}`

    let cookies = {
        '_tb_token_': global.token,
        't': new Date().getTime(),
        'v': '0',
        'cookie2': global.cookie2,
    };
    let cookie_val = utils.formatCook(cookies);
    let headers = {
        'authority': 'pub.alimama.com',
        'method': 'GET',
        'path': '/common/code/getAuctionCode.json?auctionid=575830334240&adzoneid=78346129&siteid=23532937&scenes=1&tkFinalCampaign=1&t=' + new Date().getTime() + '&_tb_token_=' + global.token + '&pvid=10_220.200.59.244_622_' + new Date().getTime(),
        'referer': 'https://pub.alimama.com/promo/search/index.htm?q=%E5%93%87%E5%93%88%E5%93%88ad%E9%92%99%E5%A5%B6220ml&_t=1536243536417&toPage=1&dpyhq=1',
        'x-requested-with': 'XMLHttpRequest',
        'Cookie': cookie_val,
    };
    let resInfo = await  RequestDown(url, {}, headers)
}


var updateUserMoney = async function () {
    let OrderInfos = await  sqlOrm.taobaokeOrder.findAsync({payStatusCode: 3, share: 1});
    if (OrderInfos.length <= 0) return
    for (var order of OrderInfos) {

        if (new Date().getTime() - order.orederTime >= global.payEndTime * 24 * 3600 * 1000) {
            let money = JSON.parse(order.mayPay)
            if (money == 0) continue
            let UserInfo = await sqlOrm.app_account.findAsync({account: order.userId});
            if (UserInfo.length <= 0) {
                console.error("订单没找到用户，请手动查询")
                continue
            }

            // UserInfo[0].needBackMoney = JSON.parse(UserInfo[0].needBackMoney) -  money
            // UserInfo[0].payStatusCode = 1
            order.toMyuser = money
            order.payStatusCode = 1;
            order.payStatus = "已返利";
            order.updateTime = utils.changeToStringDate(new Date().getTime())// new Date().toLocaleString();

            if (UserInfo[0].blackUser == 1) {
                order.share = 0
                UserInfo[0].money = 0
                await order.saveAsync();
                await  UserInfo[0].saveAsync();
                return
            }

            await order.saveAsync();
            let shareMoney = 0
            if (UserInfo[0].shareId > 0) {
                let shareUser = await  sqlOrm.app_account.findAsync({account: UserInfo[0].shareId});
                if (shareUser.length > 0) {
                    shareUser[0].shareMoney += Math.round(money * 0.1)
                    var shareshareMoney = 0;
                    if (shareUser[0].shareId > 0) {
                        shareshareMoney = 100
                    }
                    let sharesumMayPayEd = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT sum(mayPay) sumMayPay FROM taobaokeorde WHERE userId = ? and share = 1 and payStatusCode = 1", [shareUser[0].account])
                    if (sharesumMayPayEd.length > 0)
                        shareUser[0].money = JSON.parse(sharesumMayPayEd[0].sumMayPay) - JSON.parse(shareUser[0].moneyBake) + JSON.parse(shareUser[0].shareMoney) + shareshareMoney

                    await shareUser[0].saveAsync()
                    shareMoney = 100
                }
            }

            let sumMayPayEd = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT sum(mayPay) sumMayPay FROM taobaokeorde WHERE userId = ? and share = 1 and payStatusCode = 1", [order.userId])
            if (sumMayPayEd.length > 0)
                UserInfo[0].money = JSON.parse(sumMayPayEd[0].sumMayPay) - JSON.parse(UserInfo[0].moneyBake) + JSON.parse(UserInfo[0].shareMoney) + shareMoney

            let sumMayPay = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT sum(mayPay) sumMayPay FROM taobaokeorde WHERE userId = ? and share = 1 and payStatusCode in (2,3)", [order.userId])
            if (sumMayPay.length > 0)
                UserInfo[0].needBackMoney = sumMayPay[0].sumMayPay

            await  UserInfo[0].saveAsync();
        }
    }
}


// 修改渠道名字
var changeChannelName = async function (channelName, adzoneid) {

    let url = 'https://pub.alimama.com/common/adzone/selfAdzoneCreate.json';
    var t = new Date().getTime()

    let params = {
        'adzoneid': adzoneid,
        'unitname': channelName,
        't': t,
        '_tb_token_': global.token,
        'pvid': '60_220.200.58.181_426_' + t,
    }

    let cookies = {
        '_tb_token_': global.token,
        't': "7013840eaba71bb502e4b38f6c792db6",
        'v': '0',
        'cookie2': global.cookie2,
    };
    let cookie_val = utils.formatCook(cookies);
    let headers = {
        'origin': 'https://pub.alimama.com',
        'authority': 'pub.alimama.com',
        'method': 'POST',
        'path': '/common/adzone/selfAdzoneCreate.json',
        'referer': 'https://pub.alimama.com/promo/search/index.htm?q=asd&_t=1537547202752',
        'x-requested-with': 'XMLHttpRequest',
        "Cookie": cookie_val
    }

    let selfAdzoneCreate = await RequestPostFom(url, params, headers);
    if (selfAdzoneCreate.data) {
        return 1
    } else {
        return 0
    }
}
// 获取订单信息
var getOrderInfoCook = async function (sendTime, orderArray, page) {


    let url = 'https://pub.alimama.com/report/getTbkPaymentDetails.json?';
    var t = new Date().getTime()
    let startTime = utils.changeToString(new Date());
    let entTime = new Date().getTime() - 30 * 24 * 3600 * 1000
    entTime = utils.changeToString(new Date(entTime))

    let lastTimeMysql = await sqlOrm.taobaokeOrder.findAsync({share: 1, payStatusCode: [2, 3]}, 1, ["createTime", "A"])
    if (lastTimeMysql.length > 0) {
        entTime = lastTimeMysql[0].createTime
    }
    if (sendTime) {
        entTime = sendTime
    }
    let params = {
        'startTime': entTime,
        'endTime': startTime,
        'payStatus': "",
        'queryType': 1,
        'toPage': page,
        'perPageSize': 100,
        't': t,
        '_tb_token_': global.token,
    };

    let cookies = {
        '_tb_token_': global.token,
        't': "7013840eaba71bb502e4b38f6c792db6",
        'v': '0',
        'cookie2': global.cookie2,
    };
    let cookie_val = utils.formatCook(cookies);
    let headers = {
        'origin': 'https://pub.alimama.com',
        'authority': 'pub.alimama.com',
        'method': 'POST',
        'path': '/common/adzone/selfAdzoneCreate.json',
        'referer': 'https://pub.alimama.com/promo/search/index.htm?q=asd&_t=1537547202752',
        'x-requested-with': 'XMLHttpRequest',
        "Cookie": cookie_val
    }

    let orderInfo = await RequestGet(url, params, headers);
    orderInfo = utils.changeToObj(orderInfo)
    // console.log("orderInfoxxxxxxxxxxxxxxxxxxx",JSON.stringify(orderInfo))
    if (orderInfo.data) {
        if (orderInfo.data.paymentList.length >= 100) {
            console.log("orderInfoxxxxxxxxxxxxxxxxxxx再次查询")
            setTimeout(async function () {
                await  getOrderInfoCook(entTime, [], page + 1)
            }, 60 * 1000)
        }
        orderArray.push(...orderInfo.data.paymentList)
        console.log("orderInfoxxxxxxxxxxxxxxxxxxx在这里赋值")
        await updateOrderInfo(orderArray)
        return 1
    } else {
        console.error("getOrderInfoCook 查询错误")
        return 0
    }
}

// 获取退款
var getMoneyBackOrder = async function (page) {
    console.log("44444444444444", page)
    let url = 'https://pub.alimama.com/report/getNewTbkRefundPaymentDetails.json?';
    var t = new Date().getTime()
    let startTime = utils.changeToString(new Date());
    let entTime = new Date().getTime() - 30 * 24 * 3600 * 1000
    entTime = utils.changeToString(new Date(entTime))
    let params = {
        'startTime': entTime,
        'endTime': startTime,
        'refundType': "1",
        'searchType': 1,
        'toPage': page,
        'perPageSize': 100,
        't': t,
        '_tb_token_': global.token,
        '_input_charset': "utf-8",
    }

    let cookies = {
        '_tb_token_': global.token,
        't': "7013840eaba71bb502e4b38f6c792db6",
        'v': '0',
        'cookie2': global.cookie2,
    };
    let cookie_val = utils.formatCook(cookies);
    let headers = {
        'origin': 'https://pub.alimama.com',
        'authority': 'pub.alimama.com',
        'method': 'POST',
        'path': '/common/adzone/selfAdzoneCreate.json',
        'referer': 'https://pub.alimama.com/promo/search/index.htm?q=asd&_t=1537547202752',
        'x-requested-with': 'XMLHttpRequest',
        "Cookie": cookie_val
    }

    let orderInfo = await RequestGet(url, params, headers);
    orderInfo = utils.changeToObj(orderInfo)

    if (orderInfo.data) {
        if (orderInfo.data.pagelist.length >= 100) {
            setTimeout(async function () {
                await  getMoneyBackOrder(page + 1)
            }, 1000)
        }
        for (var i of orderInfo.data.pagelist) {
            console.log("iiiiiiiiii", i)
            let tbTradeId = i.tbTradeId
            let tbTradeParentId = i.tbTradeParentId
            let refundFee = i.refundFee
            let payBackOrderInfo = await sqlOrm.taobaokeOrder.findAsync({
                taobaoTradeParentId: tbTradeParentId,
                taobaoTradeSubId: tbTradeId,
                totalAlipayFeeString: refundFee,
                payStatusCode: 1
            })
            if (payBackOrderInfo.length > 0) {
                payBackOrderInfo[0].payStatusCode = -1;
                payBackOrderInfo[0].payStatus = "已退款";
                payBackOrderInfo[0].saveAsync()
            }
        }

    } else {
        return 0
    }
}




var getPddOrders = async function (page){

    try {
        let postUrl = "http://gw-api.pinduoduo.com/api/router";
        let postVaule = {
            'client_id': `${config.client_id}`,
            'type': 'pdd.ddk.order.list.increment.get',
            'timestamp': `${Math.floor(new Date().getTime()/1000)}`,
            'data_type': 'JSON',
            'order_status': '5',
            'start_update_time': Math.floor(new Date().getTime()/1000),
            'end_update_time': Math.floor(new Date().getTime()/1000),
            'page': 1 ,
            'page_size': 50 ,
        };

        let SignStr = utils.MakeStr(postVaule);
        let sign = utils.PDDSign(SignStr);
        postVaule.sign = sign;
        console.log("11111111",postVaule)
        let resInfo = await requestPost(postUrl,postVaule);

        console.log("getPddOrders resInfo is:",resInfo);
        if(resInfo && resInfo.order_list_get_response){
            console.log("resInfo is:",resInfo.order_list_get_response.order_list);
            return resInfo.order_list_get_response.order_list
        }
        return null
    }catch (e) {
        return null
    }
}

function sleep(d) {
    for (var t = Date.now(); Date.now() - t <= d;) ;
}

module.exports = InitSelf = new Init();
